package com.linsen.core.common.util;

import cn.hutool.core.util.ObjectUtil;
import com.linsen.core.common.enums.OsTypeEnum;
import lombok.experimental.UtilityClass;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 操作系统工具类
 * @ProjectName: ccadult-work-weixin-platform
 * @Package: com.lanshan.commons.tools.utils
 * @ClassName: OsUtils
 * @Author: zhaoyong
 * @Email: zy765203718@gmail.com
 * @Date: 2023/4/12 14:55
 * @Version: 1.0
 */
@UtilityClass
public final class OsUtils {

    /** 获取Request请求对应的操作系统类型 */
    public OsTypeEnum getOsType(HttpServletRequest request) {
        return getOsType(request.getHeader(HttpHeaders.USER_AGENT));
    }

    /** 获取Request请求对应的操作系统类型 */
    public OsTypeEnum getOsType(String userAgent) {
        if (ObjectUtil.isNotEmpty(userAgent)){
            userAgent = userAgent.toLowerCase();
            for (OsTypeEnum osTypeEnum : OsTypeEnum.values()) {
                if (regex(osTypeEnum.value(),userAgent)){
                    return osTypeEnum;
                }
            }
        }

        return OsTypeEnum.UNKNOWN;
    }

    public boolean regex(String regex, String str) {
        Pattern p = Pattern.compile(regex, Pattern.MULTILINE);
        Matcher m = p.matcher(str);
        return m.find();
    }
}
